﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Xml;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

namespace Frw.DAL
{
    public interface IStoreProcedureExecutor
    {
        T ExecuteQuery<T>(SqlCommand cmd);
    }

    public class StoreProcedureExecutor : IDisposable
    {
        SqlCommand m_cmd = null;

        public SqlCommand Command
        {
            get { return m_cmd; }
            set { m_cmd = value; }
        }

        public StoreProcedureExecutor()
        {

        }

        public StoreProcedureExecutor(SqlCommand cmd) : this()
        {
            m_cmd = cmd;

            if (m_cmd != null)
            {
                m_cmd.Connection.Open();
            }
            else
            {
                throw new ArgumentNullException("SqlCommand command is null !");
            }
        }

        public int ExecuteQuery()
        {
            int retValue = m_cmd.ExecuteNonQuery();

            return retValue;
        }

        public SqlDataReader ExecuteQuerySqlDataReader()
        {
            SqlDataReader retValue = m_cmd.ExecuteReader();

            return retValue;
        }

        public T ExecuteNonQuery<T>()
        {
            T retValue = (T)m_cmd.ExecuteScalar();

            return retValue;
        }

        public XmlReader ExecuteQueryXmlReader()
        {
            XmlReader retValue = m_cmd.ExecuteXmlReader();
            
            return retValue;
        }

        public ObjectResult<T> ExecuteQueryObjectResult<T, OC>()
            where T : ComplexObject
            where OC : ObjectContext, new()
        {
            ObjectResult<T> retValue = null;

            OC m_oc = new OC();
            var reader = m_cmd.ExecuteReader();
            retValue = m_oc.Translate<T>(reader);

            return retValue;
        }

        public void Dispose()
        {
            m_cmd.Connection.Close();
            m_cmd = null;
        }
    }
}
